#include <cassert>
#include <rtppacket.h>
#include "RTPReciever.h"

using namespace ipsound;

void checkerror( int rtperr )
{
	assert ( rtperr >= 0 );
}

RTPReciever::RTPReciever( MutexBuffer* buffer, const HANDLE playEvent )
:buffer( buffer )
,bytesRecieved( 0 )
,playEvent( playEvent )
,soundIsPlaying( false )
{
}

RTPReciever::~RTPReciever()
{
}

void RTPReciever::OnPollThreadStep()
{
	BeginDataAccess();

	if (GotoFirstSourceWithData())
	{
		do
		{
			RTPPacket *pack;			
			while ((pack = GetNextPacket()) != NULL)
			{
				buffer->Write( pack->GetPayloadData(), pack->GetPayloadLength() );
				bytesRecieved += pack->GetPayloadLength();

				if ( bytesRecieved > (buffer->GetSize() / 2) && !soundIsPlaying )
				{
					SetEvent( playEvent );
					soundIsPlaying = true;
				}

				DeletePacket(pack);
			}
		} while (GotoNextSourceWithData());
	}
		
	EndDataAccess();
}